<?php #Редактор страниц
class page_editor extends Load_use
{
	private $redirect = false;
	private $table_brands = '';
	private $page_fields_arr = array('id','parents','title','h1','text1','text2','url','templ','meta_title','meta_description','meta_robots','meta_keywords','meta_accusative_case','сat_plural');	

	function getBlock()
	{
		// $this->getSortedBrands();
		$block = '';
		$page_id=$this->getParam('page_id',false);
		if($page_id )
		{
			$whisout_attaches=$this->getParam('whisout_attaches',false);
			$dont_change_templ=$this->getParam('dont_change_templ',false);
			$dont_change_parents=$this->getParam('dont_change_parents',false);
			$page=false;
			$fields_names=$fields_names_arr=array('title'=>'Название страницы (текст тега title)','text1'=>'Основной текст','text2'=>'Дополнительный текст');
			if($page_id=='new')
			{
				/*Дефолтные значения полей*/
				$page=(object)array('title'=>'','id'=>'','url'=>'','text1'=>'','text2'=>'','meta_description'=>'','meta_robots'=>'','meta_keywords'=>'','meta_accusative_case'=>'','сat_plural'=>'','meta_title'=>'','h1'=>'','parents'=>$this->getParam('parents',''),'templ'=>($dont_change_templ?$dont_change_templ:'_simple'),'adding'=>true,'date_last_edit'=>'','date_create'=>'','editor_name'=>'','creator_name'=>'');
				$this->view->js_on_load[]='$(".page-editor .form_control .activate").click()';				
			}
			else
			{
				$id=mysql_escape_string($page_id);
				$this->conn->query("select p.*,uc.name as creator_name,ur.name as editor_name from pages p join users ur on ur.id=p.editor_id join users uc on uc.id=p.creator_id where p.id=$id");
				$page=$this->conn->fetch();
				$page->adding=false;
			}
			if(!$page)return '';
			
			$cache=$this->cache->get('admin/site_templs','get_comment_params','templ');
			/*Список шаблонов*/
			$template_arr=array();
			if(isset($cache['templs']))
				$template_arr=$cache['templs'];
				
			/*Обработка формы редактирования страницы*/
			if(!empty($_POST['page_edit']))
			{
				$err=array();
				$edit=$_POST['page_edit'];
				/*Генерация и преобразование УРЛ*/
				$edit['url']=getGoodUrl($edit[empty($edit['url'])?'title':'url']);
			 	if(empty($edit['url'])&&empty($edit['title']))
					$err[]='<li>Страницу нельзя создать без УРЛ, поле заголовка пусто, заполните его, чтобы сгенерировать УРЛ либо введите его вручную. Не допустимые символы будут удалены.</li>';
				if(empty($edit['templ']) ||!isset($template_arr[$edit['templ']]))
					$err[]='<li>Ошибка с выбранным шаблоном, попробуйте выбрать его еще раз.</li>';
				if($err)
				{
					$this->view->js_on_load[]='dee_corner.quick_message("<ul>'.implode($err).'</ul>","'.DEE_ERROR.'")';
					//$this->load->block('modal_win',array('title'=>'Ошибка при заполнении','cont'=>'<ul>'.implode($err).'</ul>','class'=>'errors'));					 
				}
				else
				{
					$data=array();					
					 foreach($this->page_fields_arr as $name)
						$data[$name]=empty($edit[$name])?'':mysql_escape_string($edit[$name]);
						
					$adm_page=!empty($_GET['p'])?$_GET['p']:'_pages';
					/*Добавляю страницу*/
					if($page->adding)
					{
						$page_id=$this->conn->query("insert into pages (parents, title, h1, text1, text2, url, templ, meta_title, meta_description, meta_robots, meta_keywords, meta_accusative_case, сat_plural, editor_id, creator_id, date_create ) values ( '{$data['parents']}', '{$data['title']}', '{$data['h1']}', '{$data['text1']}', '{$data['text2']}', '{$data['url']}', '{$data['templ']}', '{$data['meta_title']}', '{$data['meta_description']}', '{$data['meta_robots']}', '{$data['meta_keywords']}', '{$data['meta_accusative_case']}', '{$data['сat_plural']}', {$this->user->id}, {$this->user->id}, now() );",true);
						if($page_id)
						{
							$this->redirect=array('url'=>'/admin?p='.$adm_page.'&par='.urlencode($data['parents'].'#'.$page_id.'#').'&edit_id='.$page_id.'#page_edit','message'=>'Страница создана');
							$page->id=$page_id;
						}
					}
					/*Обновляю*/
					else
					{
						/*Обновляю страницу*/
						$this->conn->query("update pages set parents='{$data['parents']}', title='{$data['title']}', h1='{$data['h1']}', text1='{$data['text1']}', text2='{$data['text2']}', url='{$data['url']}', templ='{$data['templ']}', meta_title='{$data['meta_title']}', meta_description='{$data['meta_description']}', meta_robots='{$data['meta_robots']}', `meta_keywords` = '{$data['meta_keywords']}', `meta_accusative_case` = '{$data['meta_accusative_case']}', `сat_plural` = '{$data['сat_plural']}', `editor_id` = {$this->user->id} WHERE `id` = {$page->id}");
						/*Если изменен раздел то переношу подразделы страницы*/
						if($edit['parents_old']!=$edit['parents'])
						{
							$parents_old=mysql_escape_string($edit['parents_old']);
							$this->conn->query("update pages set parents=replace(parents,'$parents_old#{$page->id}#','{$data['parents']}#{$page->id}#') where parents like '$parents_old#{$page->id}#%'");
						}
						$this->redirect=array('url'=>'/admin?p='.$adm_page.'&par='.urlencode($data['parents'].'#'.$page->id.'#').'&='.$page->id.'#page_edit','message'=>'Страница обновлена');
						/*Если изменился то удаляю приложения старого шаблона*/
						if($edit['templ_old']!=$edit['templ'])
							$this->conn->query("delete from pages_attachments where page_id={$page->id}");
					}
				}
				foreach($this->page_fields_arr as $name)
					if(isset($edit[$name]))
						$page->$name=$edit[$name];
			}
			
			$parents=$this->getParents($page->parents);
			$block='<div class="page-editor fields-editor">
				<div class="attaches add_prototype">';
			$current_templ_attaches=array();			 
			/*Параметры шаблонов*/
			if(!empty($cache['params']))
			{
				$js_field_descs=array();
				foreach($cache['params'] as $templ_name=>$p)				
				if(!empty($p))
				{
					if(!empty($p['fields_names']))
					{
						if($templ_name==$page->templ)
							$fields_names=array_merge($fields_names_arr,$p['fields_names']);
						$js_field_descs[$templ_name]=$p['fields_names'];
					}	
					if(!empty($p['attaches']))
					{
						if(!$dont_change_templ)
						{
							$block.='<div class="attach-'.$templ_name.'">'
								.$this->load->module('attaches','getAttaches',array('attaches'=>$p['attaches'],'clear'=>true))
							.'</div>';
						}
						if($templ_name==$page->templ)
						{						
							$current_templ_attaches=$p['attaches'];
						}
					}					
				}
				if(!empty($js_field_descs))
				{
					$js_field_descs['defaults']=$fields_names_arr;
					$this->view->js_on_load[]='page_editor.field_descs='.getJSArr($js_field_descs);
				}
			}		
			$js_css='';
			if(!$whisout_attaches)
			{
				$js_css=$this->load->module('attaches','getAttaches',array('attaches'=>array(
				array('type'=>'file','desc'=>'JS файлы','name'=>'_js_load','params'=>array('root_path'=>'js/site','extensions'=>array('js'))),
				array('type'=>'file','desc'=>'CSS файлы','name'=>'_css_load','params'=>array('root_path'=>'css/site','extensions'=>array('css'))),
				),'page_id'=>$page->id,'only_templ'=>true))	;
				$current_templ_attaches=$this->load->module('attaches','getAttaches',array('attaches'=>$current_templ_attaches,'page_id'=>$page->id));
			}
			else $current_templ_attaches='';
			
/* 			if($this->redirect)
			{
				if(!isset($this->params['redirect']) || $this->params['redirect'])
					successRedirect($this->redirect);
				else
					return $page_id;
			} */
			$block.='<div class="clear"></div></div>
				<div class="editor_block form" id="page_edit">
				<div class="title"><span>Основное</span>'
					.$this->load->block('form_control',array('controls'=>array('edit'),'title'=>'Страница'))
				.'</div>
				<div class="to_save">
					<div class="page">						
						<div class="data">
							<div class="field">
								<div class="desc"><span class="templ_param_name-title">'.$fields_names['title'].'</span>:</div>'				
								.$this->load->block('form_element',array('readonly'=>true,'name'=>'page_edit[title]','val'=>$page->title))
							.'</div>'
							.($dont_change_parents
								?''
								:'<div class="field">
									<div class="desc">Раздел:</div>'				
									.$this->load->block('form_element',array('readonly'=>true,'attr'=>' onclick="page_editor.getSelect(this,'.($page->adding?'false':$page->id).')" ','class'=>'parents disabled','val'=>$parents['names']))
									.'<input type="hidden" class="new" name="page_edit[parents]" value="'.$page->parents.'" />
									<input type="hidden" name="page_edit[parents_old]" value="'.$page->parents.'" />
								</div>'
							)
							.($dont_change_templ
								?'<input type="hidden" name="page_edit[templ]" value="'.$dont_change_templ.'" />'
								:'<div class="field">
									<div class="desc">Шаблон:</div>'				
									.$this->load->block('form_element',array('readonly'=>true,'attr'=>' onchange="page_editor.changeTempl(this)"','name'=>'page_edit[templ]','val'=>$page->templ,'type'=>'select','values'=>$template_arr))
									.'<input type="hidden" name="page_edit[templ_old]" value="'.$page->templ.'" />
								</div>'
							)
							.'<div class="field templ_description">
								<div class="desc">'
									
								.'</div>'
								.($page->adding && $page->templ!='_main'?'':'<a href="'.$parents['url'].'/'.$page->url.'">Перейти на страницу</a>')
							.'</div>
							<div class="clear"></div>
							<div class="field text_big">
								<div class="desc"><span class="templ_param_name-text1">'.$fields_names['text1'].'</span>:</div>'				
								.$this->load->block('form_element',array('type'=>'textarea','readonly'=>true,'name'=>'page_edit[text1]','val'=>$page->text1))
							.'</div>
							<div class="field text_big">
								<div class="desc"><span class="templ_param_name-text2">'.$fields_names['text2'].'</span>:</div>'				
								.$this->load->block('form_element',array('type'=>'textarea','readonly'=>true,'name'=>'page_edit[text2]','val'=>$page->text2))
							.'</div>
							<div class="clear"></div>
							<div class="js_css">'							
								.$js_css						
							.'</div>
							<div class="attaches_place">'
								.$current_templ_attaches
							.'</div>
							<div class="clear"></div>
						</div>
					</div>';
					
			if( $page->templ == 'category' || $page->templ == 'sub_category' )
				$block .='
				<div class="category_filter">
					<div class="title" onclick="showHide(\'.data#category_filter\')"><span>Выбор полей для фильтра товаров:</span></div>
					<div class="data" id="category_filter"  style="display:none">
						'.$this->load->block( 'select_charact', array( 'page_id' => $page->id, 'parents' => $page->parents.'#'.$page->id.'#' ) ).'
					</div>
				</div>';
			
																
			$block.='<div class="seo">	
						<div class="title" onclick="showHide(\'.data#seo\')"><span>СЕО данные</span></div>
						<div class="data" id="seo">		
							<div class="field text_small">
								<div class="desc">Meta description:</div>'				
								.$this->load->block('form_element',array('type'=>'textarea','readonly'=>true,'name'=>'page_edit[meta_description]','val'=>$page->meta_description))
							.'</div>
							<div class="field">
								<div class="desc">Meta title:</div>'				
								.$this->load->block('form_element',array('readonly'=>true,'name'=>'page_edit[meta_title]','val'=>$page->meta_title))
							.'</div>
							<div class="field">
								<div class="desc">Meta robots:</div>'				
								.$this->load->block('form_element',array('readonly'=>true,'name'=>'page_edit[meta_robots]','val'=>$page->meta_robots))
							.'</div>	
							<div class="field">
								<div class="desc">Meta keywords:</div>'				
								.$this->load->block('form_element',array('readonly'=>true,'name'=>'page_edit[meta_keywords]','val'=>$page->meta_keywords))
							.'</div>
							<div class="field">
								<div class="desc">Текст тега h1:</div>'				
								.$this->load->block('form_element',array('readonly'=>true,'name'=>'page_edit[h1]','val'=>$page->h1))
							.'</div>
							<div class="field">
								<div class="desc">Категория в винительном падеже</div>'				
								.$this->load->block('form_element',array('readonly'=>true,'name'=>'page_edit[meta_accusative_case]','val'=>$page->meta_accusative_case))
							.'</div>
							<div class="field">
								<div class="desc">Категория во множественном числе</div>'				
								.$this->load->block('form_element',array('readonly'=>true,'name'=>'page_edit[сat_plural]','val'=>$page->сat_plural))
							.'</div>
							<div class="field">
								<div class="desc">URL страницы:</div>'				
								.$this->load->block('form_element',array('readonly'=>true,'name'=>'page_edit[url]','val'=>$page->url))
							.'</div>
							<div class="clear"></div>
						</div>
					</div>
					
					<div class="more">
						<div class="title" onclick="showHide(\'.data#more\')"><span>Дополнительно</span></div>		
						<div class="data" id="more">
							<div class="field">'
							.(!$whisout_attaches
								?'</div>
									<div class="field">
										<div class="desc">Приложения:</div>'				
										.$this->load->block('form_element',array('type'=>'select','readonly'=>true,'values'=>array('js'=>'Файл JS','css'=>'Файл CSS','block'=>'Блок')))
										.$this->load->block('buttons',array('style'=>'add','attr'=>'disabled="disabled" onclick="page_editor.addAttach(this)"','text'=>'Добавить приложение'))
								:''
							)
							.'</div>
							<div class="clear"></div>'
								.(!$page->adding?'<div class="field">
									<div class="desc">Создатель страницы:</div><b>'
										.$page->creator_name
								.'</b></div>
								<div class="field">
									<div class="desc">Дата создания:</div>'
										.$page->date_create
								.'</div>
								<div class="field">
									<div class="desc">Последний редактор страницы:</div><b>'
										.$page->editor_name
								.'</b></div>
								<div class="field">
									<div class="desc">Дата последнего редактирования:</div>'
										.$page->date_last_edit
								.'</div>
								<div class="clear"></div>':'')
								.$this->table_brands.'
						</div>
					</div>
				</div>
			</div></div><script type="text/javascript">fc_one_button=true;</script>';
			
				
		};
		return $block;
	}
	
	function getParents($parents)
	{
		$res=array('names'=>'Корень','url'=>'');
		if(!empty($parents))
		{
			$parents_ids=getIdsArr($parents);
			$this->conn->query('select title,id,url from pages where id in('.implode(',',$parents_ids).') order by parents');
			$parents_arr=array();
			while($row=$this->conn->fetch())
				$parents_arr[$row->id]=$row;
			foreach($parents_ids as $id)
			{
				$title=$url='';
				if(isset($parents_arr[$id]))
				{
					$title=$parents_arr[$id]->title;
					$url=$parents_arr[$id]->url;
				}
				else
					$title=$id;
				$res['names'].=' => '.$title;
				$res['url'].='/'.$url;
			}
		}
		return $res;
	}
	function getSortedBrands()
	{
		$page_id = isset( $_GET['edit_id'] ) ? $_GET['edit_id'] : '';
		if( isset( $_GET['templ'] ) && $_GET['templ'] == 'sub_category' && $page_id )
		{
			$brands_list = '';
			$this->conn->query('SELECT `parents` FROM `pages` WHERE `id` = '.$page_id );
			$row = $this->conn->fetch();
			
			$parents = $row->parents.'#'.$page_id .'#';
			$this->conn->query('
				SELECT `b`.`id` AS `brand_id`, `b`.`name`, `s`.`zin` FROM `store_product_brand` AS `b`
				LEFT JOIN `store_product_brand_sort` AS `s` ON `s`.`brand_id` = `b`.`id` AND `s`.`page_id` = '.$page_id.'
				LEFT JOIN `store_products_cache` AS `p` ON `p`.`page_id` = `s`.`page_id` AND `p`.`pp` IS NOT NULL AND `p`.`price_retail` > 0
				WHERE `b`.`id` IN( SELECT `brand_id` FROM `store_products_cache` WHERE `parents` = "'.$parents.'" )
				ORDER BY `s`.`zin`, `b`.`name`
			');
			
			while( $row = $this->conn->fetch() )
			{
				$brands_list .= '
					<tr>
						<td><span class="numbers">'.$row->name.'</span></td>
						<td><input type="text" name="brands['.$row->brand_id.']" value="'.$row->zin.'" /></td>
					</tr>';
			}
			if( $brands_list )
			{
				$this->table_brands .= '
						<div class="table_brands">
							<h3>Сортировка производителей</h3>
							<table>
								'.$brands_list.'
							</table><br />
							<input type="hidden" name="page_id" value="'.$page_id.'"/>
							<input type="submit" class="send_brand_sort_list" value="Сохранить"/>
							<span  id="success_save_brand_list"></span>
						</div>';
			}
		}
	}
}
